//
//  YSReadOperation.m
//  YSBookRead
//
//  Created by MOLBASE on 2018/11/7.
//  Copyright © 2018年 YangShen. All rights reserved.
//

#import "YSReadOperation.h"
#import "YSReadBookModel.h"
#import "YSReadPageController.h"
#import "YSStorageManager.h"
#import "YSHUDManager.h"
#import "YSBookChapterModel.h"
#import "YSBookChapterContentModel.h"
#import "YSReadRecordModel.h"
#import "YSBookSummaryModel.h"
#import "YSNetworking.h"
#import "YSReadHelper.h"

const NSInteger kYSReaderAutoLoadNumber = 5;

@interface YSReadOperation () {
    BOOL _isPageBefore;
    BOOL _isAutoLoading;
    NSInteger _endIndex;
}

/// 阅读控制器
@property (nonatomic, weak) YSReadBookModel *readBook;

@property (nonatomic, strong) NSMutableArray <YSBookChapterModel *> *chapterList;

/// 阅读的数据模型
@property (nonatomic, strong, readwrite) NSMutableArray *chapterContentList;

/// 阅读记录
@property (nonatomic, strong, readwrite) YSReadRecordModel *readRecord;

/// 书籍来源
@property (nonatomic, strong, readwrite) YSBookSummaryModel *bookSummary;


/// 成功的回调Block
@property (nonatomic, copy) void (^completionBlock)(void);
/// 失败的回调Block
@property (nonatomic, copy) void (^failureBlock)(NSString *msg);

@end

@implementation YSReadOperation

/// 获取当前阅读记录的阅读View控制器
- (YSReadPageController *)getCurrentPageViewController {
    YSReadPageController *readVC = [self getReadViewControllerWithChapter:self.readRecord.readChapter page:self.readRecord.readPage];
    _isPageBefore = NO;
    return readVC;
}

/// 通过阅读历史记录来哦获取页面控制器
- (YSReadPageController *)getReadViewControllerWithChapter:(NSInteger)chaper page:(NSInteger)page {
    if (chaper >= self.chapterList.count) { return nil; }

    YSBookChapterContentModel *chapterContent = self.chapterContentList[chaper];

    if (chapterContent.chapterIndex != self.readRecord.readChapter) {
        
        // 换章节 清除之前的
        // TODO: 换章节
        [chapterContent updateContentPaging];
        if (chapterContent.chapterIndex >= 2) {
            [[self.chapterContentList objectAtIndex:chapterContent.chapterIndex-2] releaseChapter];
        }

        if (chapterContent.haveCache) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [self autoLoadNextChapters:chapterContent.chapterIndex+1];
            });
        }
    }

    if (page >= chapterContent.pageCount || page == YSReadLastPageValue || _isPageBefore) {
        page = chapterContent.pageCount - 1;
    }

    YSReadPageController *pageVC = [[YSReadPageController alloc] init];
    pageVC.chapterContentModel = chapterContent;
    pageVC.page = page;
    return pageVC;
}

/// 获取上一页控制器
- (YSReadPageController *)getAbovePageViewController {
    // 没有阅读模型
    if (!self.readBook || self.readRecord.readChapter >= self.chapterContentList.count) { return nil; }

    // 阅读记录
    YSReadRecordModel *readRecord;
    // 页码
    NSInteger page = 0;

    readRecord = self.readRecord;

    YSBookChapterContentModel *chapterContent = self.chapterContentList[readRecord.readChapter];

    // 章节Index
    NSInteger chapterIndex = chapterContent.chapterIndex;
    // 页码
    page = readRecord.readPage;
    if (page >= chapterContent.pageCount) {
        page = chapterContent.pageCount - 1;
    }

    /// 到头了
    if (chapterIndex <= 0 && page <= 0) {
        [YSHUDManager showTipHUD:@"已经是第一页了" afterDelay:1];
        return nil;
    }

    if (page <= 0) {
        // 更新
        chapterIndex -= 1;
        page = YSReadLastPageValue;
        _isPageBefore = YES;
    } else {
        page -= 1;
        _isPageBefore = NO;
    }

    return [self getReadViewControllerWithChapter:chapterIndex page:page];
}

/// 获取下一页控制器
- (YSReadPageController *)getBelowPageViewController {
    // 没有阅读模型
    if (!self.readBook || self.readRecord.readChapter >= self.chapterContentList.count) { return nil; }

    _isPageBefore = NO;

    // 阅读记录
    YSReadRecordModel *readRecord;
    // 页码
    NSInteger page = 0;

    readRecord = self.readRecord;

    YSBookChapterContentModel *chapterContent = self.chapterContentList[readRecord.readChapter];

    // 章节ID
    NSInteger chapterIndex = chapterContent.chapterIndex;
    // 页码
    page = readRecord.readPage;
    // 最后一页
    NSInteger lastPage = chapterContent.pageCount - 1;

    /// 到头了
    if (chapterIndex >= self.chapterContentList.count-1 && page >= lastPage) {
        [YSHUDManager showTipHUD:@"已经是最后一页了" afterDelay:1];
        return nil;
    }

    if (page >= lastPage) { // 加载新一章
        chapterIndex += 1;
        page = 0;
    } else {
        page += 1;
    }

    return [self getReadViewControllerWithChapter:chapterIndex page:page];
}

#pragma mark - web数据
- (void)autoLoadNextChapters:(NSInteger)chapter {
    if (_isAutoLoading) { return; }

    _isAutoLoading = YES;

    if (chapter < self.chapterContentList.count) {
        _endIndex = chapter + kYSReaderAutoLoadNumber;
        if (_endIndex >= self.chapterContentList.count) {
            _endIndex = self.chapterContentList.count-1;
        }
        for (NSInteger i = chapter; i <= _endIndex; i++) {
            [self getChapterContentWithChapter:i autoLoad:YES];
        }
        [self getChapterContentWithChapter:chapter-2 autoLoad:YES];
    }
}

#pragma mark - Public Method
/// 更新阅读记录
- (void)updateReadRecordWithChapter:(NSInteger)chapter page:(NSInteger)page {
    self.readRecord.readChapter = chapter;
    self.readRecord.readPage = page;
    [YSStorageManager saveReadRecord:self.readRecord];
}

#pragma mark - 懒加载
- (NSMutableArray *)chapterContentList {
    if (!_chapterContentList) {
        _chapterContentList = [NSMutableArray array];
    }
    return _chapterContentList;
}

#pragma mark - 回调
- (void)updateReadingBookCompletionWith:(NSString *)errorMsg {

    dispatch_async(dispatch_get_main_queue(), ^{

        if (errorMsg.length > 0) {
            // failure
            !self.failureBlock ?: self.failureBlock(errorMsg);
        } else {
            !self.completionBlock ?: self.completionBlock();
        }

        self.completionBlock = nil;
        self.failureBlock = nil;

    });
}

#pragma mark - 数据加载
- (void)updateReadingBook:(YSReadBookModel *)readBook completion:(void (^)(void))completion failure:(void (^)(NSString *))failure {

    self.readBook = readBook;
    self.completionBlock = completion;
    self.failureBlock = failure;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 获取书籍信息
        // 0. 获取小说来源（本地小说无）
        // 1. 获取章节列表
        // 2.
        // 2.1 转换章节列表 -> 章节详情列表
        // 2.2 获取阅读历史（并判断越界情况）
        // 3. 获取阅读章节+预缓存（后5章前1章）

        if (self.readBook.isLocalBook) {
            [self getBookChapterList];
        } else {
            [self getBookSummary];
        }
    });
}

/// 更新书籍来源
- (void)updateBookSummary:(YSBookSummaryModel *)summary completion:(void(^)(void))completion failure:(void(^)(NSString *))failure {

    self.completionBlock = completion;
    self.failureBlock = failure;
    self.bookSummary = summary;
    [YSStorageManager saveBookSummary:summary bookID:self.readBook.bookID];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getBookChapterList];
    });
}


/// 获取书籍来源
- (void)getBookSummary {
    self.bookSummary = [YSStorageManager getBookSummary:self.readBook.bookID];
    if (self.bookSummary) {
        [self getBookChapterList];
        return;
    }


    [self getBookSummaryList:^(NSArray *summarys, BOOL isSuccess) {
        if (!isSuccess) {
            [self updateReadingBookCompletionWith:[NSString stringWithFormat:@"%@ 获取来源出错", self.readBook.bookName]];
            return;
        }

        if (summarys.count == 0) {
            NSLog(@"本书没有免费来源 %@", self.readBook.bookName);
            [self updateReadingBookCompletionWith:@"本书没有免费来源"];
        } else {
            self.bookSummary = summarys.firstObject;
            [YSStorageManager saveBookSummary:self.bookSummary bookID:self.readBook.bookID];
            [self getBookChapterList];
        }
    }];
}

- (void)getBookSummaryList:(void (^)(NSArray *summarys, BOOL isSuccess))success {
    NSString *API = @"http://api.zhuishushenqi.com/";
    NSString *url = [NSString stringWithFormat:@"%@atoc?view=summary&book=%@", API, self.readBook.bookID];

    [YSNetworking GET:url params:nil success:^(id response) {

        if (![response isKindOfClass:[NSArray class]]) {
            success(nil, NO);
            return;
        }

        NSMutableArray *summaryArray = [NSMutableArray array];

        NSArray *summarys = response;
        for (NSDictionary *dict in summarys) {
            if (![dict isKindOfClass:[NSDictionary class]]) {
                success(nil, NO);
                return;
            }

            if ([dict[@"source"] isEqualToString:@"zhuishuvip"]) {
                continue;
            }

            YSBookSummaryModel *summary = [[YSBookSummaryModel alloc] initWithDict:dict];
            [summaryArray addObject:summary];
        }

        success(summaryArray, YES);

    } failure:^(NSError *error) {
        [YSHUDManager hide];
        NSLog(@"%@ 获取来源出错 %@", self.readBook.bookName, error);
        success(nil, NO);
    }];
}

/// 获取章节列表
- (void)getBookChapterList {

    if (!self.chapterList) {
        self.chapterList = [NSMutableArray array];
    } else {
        [self.chapterList removeAllObjects];
    }

    NSArray *bookChapterList = [YSStorageManager getBookChapterList:self.readBook.bookID summaryID:self.bookSummary.ID];
    if (bookChapterList.count > 0 ) {
        [self.chapterList addObjectsFromArray:bookChapterList];
    }

    if (self.chapterList.count > 0 && (self.readBook.isLocalBook || !self.readBook.isHaveUpdated)) {
        [self getBookReadRecord];
        return;
    }

    NSString *API = @"http://api.zhuishushenqi.com/";
    NSString *summaryID = self.bookSummary.ID;
    NSString *linkurl = [NSString stringWithFormat:@"%@atoc/%@?view=chapters", API, summaryID];

    [YSNetworking GET:linkurl params:nil success:^(id response) {

        NSArray *chapterListDict = response[@"chapters"];

        YSBookChapterModel *lastChapterModel;
        NSInteger startIndex = self.chapterList.count > 0 ? self.chapterList.count : 0;
        NSMutableArray *chapterList = [NSMutableArray array];
        for (NSInteger i = startIndex; i < chapterListDict.count; i++) {
            NSDictionary *dict = chapterListDict[i];

            YSBookChapterModel *chapterModel = [[YSBookChapterModel alloc] init];
            chapterModel.bookID = self.readBook.bookID;
            // md5下
            chapterModel.chapterID = [YSReadHelper md5:[dict objectForKey:@"link"]];
            chapterModel.chapterIndex = i;
            chapterModel.chapterName = [dict objectForKey:@"title"];
            chapterModel.chapterURL = [dict objectForKey:@"link"];

            // 设置上下章ID
            chapterModel.prevChapterID = lastChapterModel.chapterID;
            lastChapterModel.nextChapterID = chapterModel.chapterID;

            [chapterList addObject:chapterModel];
            lastChapterModel = chapterModel;
        }

        [self.chapterList addObjectsFromArray:chapterList];
        [YSStorageManager saveBookChapterList:chapterList bookID:self.readBook.bookID summaryID:self.bookSummary.ID];

        if (chapterList.count == 0) {
            NSLog(@"该源：%@ 下没有章节", self.bookSummary.name);
            [self updateReadingBookCompletionWith:@"该源下无章节，请尝试换源"];
        } else {
            [self getBookReadRecord];
        }

    } failure:^(NSError *error) {
        [YSHUDManager hide];
        NSLog(@"请求源：%@ 出错: %@", self.bookSummary.name, error);
        [self updateReadingBookCompletionWith:@"请求章节出错，请重试或换源"];
    }];
}

/// 获取阅读记录
- (void)getBookReadRecord {

    for (YSBookChapterModel *chapterModel in self.chapterList) {
        YSBookChapterContentModel *contentModel = [YSBookChapterContentModel bookChapterContentModelWith:chapterModel];
        [self.chapterContentList addObject:contentModel];
    }

    YSReadRecordModel *readRecord = [YSStorageManager getReadRecord:self.readBook.bookID];
    if (!readRecord) {
        readRecord = [YSReadRecordModel readRecordWithBookID:self.readBook.bookID];

        // 设置阅读记录 第一个章节 为 首个章节ID
        readRecord.readChapter = 0;
        readRecord.readPage = 0;

        [YSStorageManager saveReadRecord:readRecord];
    }
    self.readRecord = readRecord;

    if (self.readRecord.readChapter >= self.chapterContentList.count) {
        self.readRecord.readChapter = self.chapterContentList.count - 1;
        [YSStorageManager saveReadRecord:self.readRecord];
    }

    // 请求章节内容数据
    [self getChapterContentWithChapter:self.readRecord.readChapter autoLoad:NO];
}

/// 获取章节内容
- (void)getChapterContentWithChapter:(NSInteger)chapter autoLoad:(BOOL)autoLoad {
    if (chapter >= self.chapterContentList.count) { return; }

    YSBookChapterContentModel *chapterContent = self.chapterContentList[chapter];

    NSLog(@"开始加载载 %zd - %@ 章节", chapterContent.chapterIndex, chapterContent.chapterName);
    if (chapterContent.haveCache) {
        if (!chapterContent.isLoad) {
            chapterContent.content = [YSStorageManager getBookChapterBody:chapterContent.bookID chapterID:chapterContent.chapterID];
        }
        chapterContent.isLoad = YES;

        if (!autoLoad) {
            [chapterContent updateContentPaging];
            [self updateReadingBookCompletionWith:nil];
            [self autoLoadNextChapters:chapter+1];
        }

        if (chapter >= _endIndex) {
            _isAutoLoading = NO;
        }
        return;
    }

    [self getChapterContentWithChapter:chapter needPadingContent:!autoLoad completion:^{
        if (!autoLoad) {
            [self updateReadingBookCompletionWith:nil];
            [self autoLoadNextChapters:chapter+1];
        }
        if (chapter >= self->_endIndex) {
            self->_isAutoLoading = NO;
        }
    } failure:^(NSString *msg) {
        [self updateReadingBookCompletionWith:msg];
        if (chapter >= self->_endIndex) {
            self->_isAutoLoading = NO;
        }
    }];
}

- (void)getChapterContentWithChapter:(NSInteger)chapter needPadingContent:(BOOL)needPadingContent completion:(void(^)(void))completion failure:(void(^)(NSString *))failure {
    YSBookChapterContentModel *chapterContent = self.chapterContentList[chapter];

    NSLog(@"download %zd 章", chapter);
    NSString *link = chapterContent.chapterURL;
    NSString *parameter = [YSReadHelper encodeToPercentEscapeString:link];
    NSString *urlStr = [NSString stringWithFormat:@"http://chapter2.zhuishushenqi.com/chapter/%@",parameter];

    [YSNetworking GET:urlStr params:nil success:^(id response) {
        NSString *body = response[@"chapter"][@"body"] ?: @"";
        NSString *formatBody = [YSReadHelper formartChpaterContent:body];
        [YSStorageManager saveBookChapterBody:chapterContent.bookID chapterID:chapterContent.chapterID body:formatBody];

        chapterContent.content = formatBody;
        chapterContent.haveCache = YES;
        chapterContent.isLoad = YES;
        if (needPadingContent) {
            [chapterContent updateContentPaging];
        }

        [self.chapterList[chapter] setHaveCache:YES];
        [YSStorageManager saveBookChapterList:self.chapterList bookID:self.readBook.bookID summaryID:self.bookSummary.ID];

        !completion ?: completion();
    } failure:^(NSError *error) {
        NSLog(@"下载 %@ 章节出错: %@", chapterContent.chapterName, error);
        !failure ?: failure(@"下载章节内容出错，请重试或换源");
    }];
}

@end
